<!DOCTYPE html>
<html>
<head>
    <title>摆设桌球</title>
</head>
<body>
    <canvas id="canvas" width="900" height="500" style="background-color:#000000">
        Your browser not support Canvas!
    </canvas>
<script type="text/javascript">
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var r=10;
    var balls = [];
    function randomColor(){
        var strHex = "#";
        var arrHex = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
        var index;
        for(var i=0;i<6;i++){
            index = Math.round(Math.random()*15);
            strHex += arrHex[index];
        }
        return strHex;
    }
    function initBall(){
    var parentBall = {
            position:{x:200,y:200},
            r:r,
            color:randomColor()
        };
        var firstBall = {
            position:{x:550,y:200},
            r:r,
            color:randomColor()
        };

        for(var j=1;j<5;j++){
            for(var k=0;k<j+1;k++){
                var ball = {
                    position:{x:firstBall.position.x + j*Math.sqrt(3)*r,y:firstBall.position.y-j*r+2*k*r},
                    r:r,
                    color:randomColor()
                }
                balls.push(ball);
            }
        }
        balls.push(firstBall);
        balls.push(parentBall);
    }

    function draw(){
        //ctx.fillStyle = "#fff";
        console.log("balls:"+balls);
        for(i in balls){
        //for(var i=0;i<balls.length;i++){
            console.log("i:"+i);
            console.log("color:"+balls[i].color);
            ctx.fillStyle = balls[i].color;
            ctx.beginPath();
            ctx.arc(balls[i].position.x,balls[i].position.y,balls[i].r,0,Math.PI*2,true);
            ctx.closePath();
            ctx.fill();
        }
    }


    initBall();
    draw();
</script>
</body>
</html>